<template>
  <div v-if="plain" style="width: 100%;">
    <el-input
      placeholder="多个标签/分隔"
      v-model="tagLabels"
      show-word-limit
      @blur="inputChange"
    ></el-input>
  </div>
  <div v-else>
    <el-tag
      :key="tag"
      v-for="tag in modelValue"
      closable
      :disable-transitions="false"
      @close="handleClose(tag)"
    >
      {{ tag.tagName }}
    </el-tag>
    <el-input
      class="input-new-tag"
      v-if="inputVisible"
      v-model="inputValue"
      ref="saveTagInput"
      size="small"
      @keyup.enter.native="handleInputConfirm"
      @blur="handleInputConfirm"
    >
    </el-input>
    <el-button v-else class="button-new-tag" size="small" @click="showInput"
      >+ 标签</el-button
    >
  </div>
</template>

<script setup>
import { ref, computed, onMounted } from "vue";
const emit = defineEmits(["update:modelValue"]);

let tagLabels = ref('');

const props = defineProps({
  modelValue: { type: Array, default: [] },
  plain: { type: Boolean, default: true },
});

const inputVisible = ref(false);
const inputValue = ref("");

const handleClose = (tag) => {
  props.modelValue.splice(props.modelValue.indexOf(tag), 1);
};

onMounted(()=>{
  for(let tag of  props.modelValue){
    tagLabels.value +=  tag.tagName + '/' ;
  }
})

// const tagLabels = computed(()=>{
//   return props.modelValue.reduce((pre, curr)=> pre.tagName + "|" + curr.tagName,'')
// })

const showInput = () => {
  inputVisible.value = true;
  // this.$nextTick(_ => {
  //   this.$refs.saveTagInput.$refs.input.focus();
  // });
};

const handleInputConfirm = () => {
  const tag = inputValue.value;
  if (tag) {
    props.modelValue.push({ tagName: tag });
  }
  inputValue.value = "";
  inputVisible.value = false;
  emit("update:modelValue", props.modelValue);
};

const inputChange = (e) => {
  const tagModels = tagLabels.value.split(/[\|,\/]/g).map(tag=>{
    return {tagName: tag};
  });
  emit("update:modelValue", tagModels);
};
</script>

<style scoped>
.el-tag + .el-tag {
  margin-left: 10px;
}
.button-new-tag {
  margin-left: 10px;
  height: 32px;
  line-height: 30px;
  padding-top: 0;
  padding-bottom: 0;
}
.input-new-tag {
  width: 90px;
  margin-left: 10px;
  vertical-align: bottom;
}
</style>